import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import java.util.Date;

public class CookieDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //实现一个记录登陆时间的Cookie
        //原理是每次响应都返回一个Cookie。同时下次请求的时候带着Cookie，把带过来的Cookie内容加载到输出上。


        req.setCharacterEncoding("utf-8");
        //不设置文本格式就会乱码
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");



        PrintWriter out = resp.getWriter();
        //接收从客户端带来的Cookie
        Cookie[] cookies = req.getCookies();

        //判断Cookie是否存在
        if(cookies!=null){
            //如果存在
            //write也可以输出
            out.print("你上一次访问的时间是");
            for (int i = 0; i < cookies.length; i++) {
                //获取cookie的名字
                Cookie cookie = cookies[i];
                if(cookie.getName().equals("lastLoginTime")){
                    //获取cookie的值
                    long lastLoginTime = Long.parseLong(cookie.getValue());
                    //用时间戳初始化一个Date对象
                    Date date = new Date(lastLoginTime);
                    out.print(date.toString());
                }

            }


        }else{
            out.print("这是你第一次访问");
        }

        //服务给客户端响应一个cookie、
        Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");

        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
